package org.jeecg.modules.charge.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.entity.charge.*;
import org.jeecg.enums.InvoiceTypeEnum;
import org.jeecg.modules.charge.entity.ChargeBillsOrder;
import org.jeecg.modules.charge.service.IChargeBillsHistoryService;
import org.jeecg.modules.charge.service.IChargeBillsService;
import org.jeecg.modules.charge.service.IChargeDiscountService;
import org.jeecg.modules.charge.service.impl.ChargeInvoiceInfoServiceImpl;
import org.jeecg.modules.charge.vo.DictModel;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.vo.charge.ChargeBillsJumpAll;
import org.jeecg.vo.charge.ChargeBillsReducedRespVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 账单
 * @Author: jeecg-boot
 * @Date:   2019-08-08
 * @Version: V1.0
 */
@Slf4j
@Api(tags="账单")
@RestController
@RequestMapping("/b/charge/chargeBills")
public class ChargeBillsController {
	 @Autowired
	 private IChargeBillsService chargeBillsService;
	@Autowired
	private IChargeBillsHistoryService chargeBillsHistoryService;
	 @Autowired
	 private ChargeInvoiceInfoServiceImpl chargeInvoiceInfoService;
	 @Autowired
	 private IChargeDiscountService chargeDiscountService;
	 @Autowired
     private ISysUserRoleService sysUserRoleService;

	/**
	  * 分页列表查询
	 * @param chargeBills
	 * @return
	 */
	@AutoLog(value = "账单-分页列表查询")
	@ApiOperation(value="账单-分页列表查询", notes="账单-分页列表查询")
	@GetMapping(value = "/page")
    public Result<IPage<ChargeBills>> queryPageList(ChargeBills chargeBills,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        chargeBills.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",chargeBills.getMenuPath(),null,null));
        Page<ChargeBills> page = new Page<ChargeBills>(pageNo, pageSize);
        List<ChargeBills> list = chargeBillsService.findPage(page,chargeBills);
        page.setRecords(list);
        return Result.ok(page);
    }

	/**
	 * 分页列表查询
	 * @param chargeBills
	 * @return
	 */
	@AutoLog(value = "账单-分页列表查询")
	@ApiOperation(value="账单-分页列表查询", notes="账单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<List<ChargeBills>> queryList(ChargeBills chargeBills,HttpServletRequest req) {
		chargeBills.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",chargeBills.getMenuPath(),null,null));
		List<ChargeBills> list = chargeBillsService.findList(chargeBills);
		return Result.ok(list);
	}
	
	/**
	  *   添加
	 * @param chargeBills
	 * @return
	 */
	@AutoLog(value = "账单-添加")
	@ApiOperation(value="账单-添加", notes="账单-添加")
	@PostMapping(value = "/add")
	public Result<ChargeBills> add(@RequestBody ChargeBills chargeBills) {
		Result<ChargeBills> result = new Result<ChargeBills>();
		try {
			chargeBillsService.save(chargeBills);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param chargeBills
	 * @return
	 */
	@AutoLog(value = "账单-编辑")
	@ApiOperation(value="账单-编辑", notes="账单-编辑")
	@PutMapping(value = "/edit")
	public Result<ChargeBills> edit(@RequestBody ChargeBills chargeBills) {
		Result<ChargeBills> result = new Result<ChargeBills>();
		ChargeBills chargeBillsEntity = chargeBillsService.getById(chargeBills.getId());
		if(chargeBillsEntity==null) {
			result.error500("未找到对应实体");
		}else {
			if(chargeBillsEntity.getZjSkrq() == null && !chargeBills.getDue().toString().equals(chargeBillsEntity.getDue().toString())){
				/*chargeBillsService.deleteHistory(chargeBills.getId());*/
//				chargeBillsEntity.setId(String.valueOf(IdWorker.getId()));
				chargeBillsEntity.setParentBillsIds(chargeBills.getId());
				chargeBillsEntity.setBillsExp("原账单");
//				chargeBillsService.insertBillsHistory(chargeBillsEntity);
			}
			chargeBills.setZjTzrq(new Date());
			boolean ok = chargeBillsService.updateById(chargeBills);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		return result;
	}
	
	/**
	 * 账单作废
	 * @param id
	 * @return
	 */
	@AutoLog(value = "账单-作废")
	@ApiOperation(value="账单-作废", notes="账单-作废")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="ids",required=true) String ids) {
		try {
			if (StringUtils.isBlank(ids)){
				return Result.error("作废账单数据不能为空");
			}
			return chargeBillsService.delete(ids);
		} catch (Exception e) {
			log.error("作废失败",e.getMessage());
			return Result.error("作废失败!");
		}
	}

	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "账单-批量删除")
	@ApiOperation(value="账单-批量删除", notes="账单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<ChargeBills> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ChargeBills> result = new Result<ChargeBills>();
		try {
			if (ids == null || "".equals(ids.trim())) {
				result.error500("参数不识别！");
			} else {
				this.chargeBillsService.removeByIds(Arrays.asList(ids.split(",")));
				result.success("删除成功!");
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "账单-通过id查询")
	@ApiOperation(value="账单-通过id查询", notes="账单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ChargeBills> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ChargeBills> result = new Result<ChargeBills>();
		try {
			ChargeBills chargeBills = chargeBillsService.getById(id);
			if (chargeBills == null) {
				result.error500("未找到对应实体");
			} else {
				result.setResult(chargeBills);
				result.setSuccess(true);
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<ChargeBills> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              ChargeBills chargeBills = JSON.parseObject(deString, ChargeBills.class);
              queryWrapper = QueryGenerator.initQueryWrapper(chargeBills, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<ChargeBills> pageList = chargeBillsService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "账单列表");
      mv.addObject(NormalExcelConstants.CLASS, ChargeBills.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("账单列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ChargeBills> listChargeBillss = ExcelImportUtil.importExcel(file.getInputStream(), ChargeBills.class, params);
              chargeBillsService.saveBatch(listChargeBillss);
              return Result.ok("文件导入成功！数据行数:" + listChargeBillss.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

	 /**
	  * 根据账单id获取账单收费项
	  * @param chargeBills
	  * @return
	  */
	  @PostMapping(value = "/getFeeItemId")
	  public Result<String> getFeeItemId(@RequestBody ChargeBills chargeBills){
	  	Result result = new Result();
	  	List<ChargeBills> resultFeeItems = chargeBillsService.getFeeItemId(chargeBills.getBillIds());
	  	if (null != resultFeeItems && resultFeeItems.size() == 0){
	  		return Result.error("账单信息不能为空");
		}
		/*
	  	//存放feeitemid信息
	  	Set<String> itemIds = new HashSet();
	  	for (ChargeBills bills : resultFeeItems){
	  		itemIds.add(bills.getFeeitemId());
		}
	  	if (itemIds.size() != 1){
			return Result.error("合并收款不能选择多个收费项信息");
		}
	    ChargeBills cb = chargeBillsService.getById(chargeBills.getBillIds().get(0));
	  	//获取当前收费项下未缴费的所有账单
	    chargeBills.setFeeitemId(cb.getFeeitemId());
		List<ChargeBills> list  = chargeBillsService.getChargeBills(chargeBills);
		//所有未缴账单集合
		List<String> unPayList = list.stream().map(ChargeBills::getZjCny).distinct().collect(Collectors.toList());
		//当前勾选缴费账单时间
		List<String> payDates = resultFeeItems.stream().map(ChargeBills::getZjCny).distinct().collect(Collectors.toList());
		//缴费开始时间和账单开始时间不同
	   log.info("未缴费账单：{}，勾选缴费账单：{}",unPayList, payDates);
	   if (unPayList == null || unPayList.size() <= 0){
		   return Result.error("没有未缴费账单,请刷新页面!");
	   }
		if (!unPayList.get(0).equals(payDates.get(0))){
			log.info("缴费开始时间和账单开始时间不同");
			return Result.error("账单缴费不可以断缴");
		}
		List<String> monthBetween = DateUtils.getMonthBetween(payDates.get(0), payDates.get(payDates.size() - 1));
		//缴费日期区间和账单条数不统一
		if (monthBetween.size() != payDates.size()){
			log.info("缴费日期区间和账单条数不统一");
			return Result.error("账单缴费不可以断缴");
		}
		//判断2个集合是否完全相同
		if (!(payDates.containsAll(monthBetween) && monthBetween.containsAll(payDates))){
			return Result.error("账单缴费不可以断缴");
		}
		*/
		result.setResult(resultFeeItems.get(0).getFeeitemId());
	  	result.setSuccess(true);
	  	return result;
	  }

	 /**
	  * 根据账单ID集合 计算账单优惠信息
	  * @return
	  */
	 @PostMapping(value = "/getByChargeBills")
	 public Result<ChargeBillsReducedRespVo> getByChargeBills(@RequestBody ChargeBills chargeBills){
		 ChargeBillsReducedRespVo respVo = new ChargeBillsReducedRespVo();
		 List<ChargeBills> billsList = new ArrayList<>();
		 try {
		 	 billsList = chargeBillsService.listByBills(chargeBills.getBillIds());//查找优惠规则
			 ChargeDiscount discount = new ChargeDiscount();
			 discount.setProjectId(chargeBills.getProjectId());
			 discount.setFeeId(chargeBills.getFeeitemId());
			 discount = chargeDiscountService.getDiscount(discount);
			 //账单是否优惠
			 boolean isReduced = false;
			 if (discount != null && billsList.size() >= discount.getMonths()){
			 	isReduced = true;
			 }
			 BigDecimal totalDue = BigDecimal.ZERO;  //总应收金额
			 BigDecimal totalPayReduced = BigDecimal.ZERO; //总优惠金额
			 for (ChargeBills bills: billsList){
                 if (isReduced){//有优惠信息
                 	// (折扣账单 && 优惠模式为优惠订单可以继续优惠) || 0普通账单
                 	if ((bills.getBillType() == 1 && "1".equals(discount.getIsAgain())) || bills.getBillType() == 0){   //账单类型：0普通账单  1折扣账单
						BigDecimal due = bills.getDue(); //应收金额
						BigDecimal payReduced = bills.getPayReduced(); //原始的折扣金额
//						Double discountScale = 10 - discount.getDiscountScale();
						//折上折 - 金额
						BigDecimal discountAmount = due.subtract(payReduced).multiply(new BigDecimal(discount.getDiscountScale())).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
						bills.setPayReduced(payReduced.add(discountAmount)); //折后优惠金额
					}
                 }else{
					 bills.setPayReduced(BigDecimal.ZERO);//优惠金额
                 }
				 totalDue = totalDue.add(bills.getDue());
                 totalPayReduced = totalPayReduced.add(bills.getPayReduced());
			 }
			 respVo.setDue(totalDue);
			 respVo.setPayReduced(totalPayReduced);
			 respVo.setPay(totalDue.subtract(totalPayReduced));
			 respVo.setBillsList(billsList);
			 respVo.setIsDiscount(false);
			 respVo.setInvoiceType(InvoiceTypeEnum.INVOICE_TYPE_NO.getCode());
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
			 return Result.error("系统繁忙!");
		 }
		 return  Result.ok(respVo);
	 }

	 /**
	  * 获取缴费信息
	  * @return
	  */
	 @PostMapping(value = "/getByChargeBillsAll")
	 public Result<ChargeBillsJumpAll> getByChargeBillsAll(@RequestBody ChargeBills chargeBills){
		 Result<ChargeBillsJumpAll> result = new Result<>();
		 ChargeBillsJumpAll billsJumpAll = new ChargeBillsJumpAll();
		 try {
			 billsJumpAll = chargeBillsService.getByChargeBillsAll(chargeBills.getBillIds());
			 result.setResult(billsJumpAll);
			 result.setSuccess(true);
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
		 }
		 return  result;
	 }

	 /**
	  * 获取缴费信息
	  * @return
	  */
	 @PostMapping(value = "/getMethodUser")
	 public Result<ChargeBillsJumpAll> getMethodUser(){
		 Result<ChargeBillsJumpAll> result = new Result<>();
		 ChargeBillsJumpAll billsJumpAll = new ChargeBillsJumpAll();
		 try {
			 billsJumpAll = chargeBillsService.getMethodUser();
			 result.setResult(billsJumpAll);
			 result.setSuccess(true);
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
		 }
		 return  result;
	 }



	 /**
	  * 订单详细列表
	  * @param chargeBillsOrder
	  * @return
	  */
	 @RequestMapping(value = "/listByBills", method = RequestMethod.GET)
	 public Result<List<ChargeBills>> listByBills(ChargeBillsOrder chargeBillsOrder) {
//		 Result<List<ChargeBills>> result = new Result<>();
		 String billIds = chargeBillsOrder.getBillids();
		 if (billIds == null) {
			 return Result.ok();
		 }
		 List<ChargeBills> chargeBills = new ArrayList<>();
		 if (1 == chargeBillsOrder.getRefundStatus()){
			 chargeBills =  chargeBillsHistoryService.listByBills(Arrays.asList(billIds.split(",")));
			 for (ChargeBills bills:chargeBills) {
				 bills.setZjSk("未销账");
				 if (bills.getZjSkrq() != null){
					 bills.setZjSk("已退款");
				 }
			 }
		 } else {
			 chargeBills = chargeBillsService.listByBills(Arrays.asList(billIds.split(",")));
			 for (ChargeBills bills:chargeBills) {
				 bills.setZjSk("未销账");
				 if (bills.getZjSkrq() != null){
					 bills.setZjSk("已销帐");
				 }
			 }
		 }
		 return Result.ok(chargeBills);
	 }

	 /**
	  * 无账单详细列表
	  * @param chargeBillsOrder
	  * @return
	  */
	 @RequestMapping(value = "/invoiceBills", method = RequestMethod.GET)
	 public Result<List<ChargeBills>> invoiceBills(ChargeBillsOrder chargeBillsOrder) {
		 Result<List<ChargeBills>> result = new Result<>();
		 if (chargeBillsOrder != null && chargeBillsOrder.getBillids() != null){
			 result.setResult(null);
			 List<ChargeBills>  chargeBills= chargeBillsService.getChargeBillsByInvoiceId(chargeBillsOrder.getBillids());
			 for (int i = 0; i < chargeBills.size(); i++) {
				 if (chargeBills.get(i).getZjSkrq() == null){
					 chargeBills.get(i).setZjSk("未销账");
				 }else {
					 chargeBills.get(i).setZjSk("已销帐");
				 }
			 }
			 result.setResult(chargeBills);
		 }
		 result.setSuccess(true);
		 return result;
	 }



	 /**
	  * 根据收费项目编号获取税率与财务科目
	  * @return
	  */
	 @RequestMapping(value = "/getByFeeCode")
	 public Result<ChargeFeeitem> getByFeeCode(@RequestParam(name="code",required=true) String code,
											   @RequestParam(name="projectId",required=true) String projectId){
		 Result<ChargeFeeitem> result = new Result<>();
		 ChargeFeeitem feeitem  = new ChargeFeeitem();
		 try {
			 if(StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(projectId)){
				  feeitem = chargeBillsService.getByFeeCode(code,projectId);
			 }
			 result.setResult(feeitem);
			 result.setSuccess(true);
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
		 }
		 return  result;
	 }


	 /**
	  * 获取房屋性质
	  * @return
	  */
	 @RequestMapping(value = "/getRoomproperty", method = RequestMethod.GET)
	 public Result<List<DictModel>> getRoomproperty() {
		 Result<List<DictModel>> result = new Result<>();
		 try {
			 List<DictModel> roomproperty =  chargeBillsService.getRoomproperty();
			 result.setResult(roomproperty);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }
	 /**
	  * 其他收费列表
	  * @param
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "其他收费列表")
	 @ApiOperation(value="其他收费列表", notes="其他收费列表")
	 @GetMapping(value = "/otherList")
	 public Result<Page<ChargeInvoiceInfo>> otherList(ChargeInvoiceInfo chargeInvoiceInfo,
													  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req) {
		 Result<Page<ChargeInvoiceInfo>> result = new Result<Page<ChargeInvoiceInfo>>();
		 try{
			 Page<ChargeInvoiceInfo> pageList = new Page<ChargeInvoiceInfo>(pageNo,pageSize);
			 pageList = chargeInvoiceInfoService.getOtherInvoice(pageList,chargeInvoiceInfo);//通知公告消息
			 result.setSuccess(true);
			 result.setResult(pageList);
		 }catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }

		 return result;
	 }

	 /**
	  * 收费情况查询列表
	  * @param
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "收费情况查询")
	 @ApiOperation(value="收费情况查询", notes="收费情况查询")
	 @GetMapping(value = "/getChargeBillsAll")
	 public Result<IPage<ChargeBills>> getChargeBillsAll(ChargeBills chargeBills,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		 Result<IPage<ChargeBills>> result = new Result<IPage<ChargeBills>>();
		 try {
			 Page<ChargeBills> page = new Page<ChargeBills>(pageNo, pageSize);
			 page.setRecords(chargeBillsService.getChargeBillsAll(page,chargeBills));
			 result.setSuccess(true);
			 result.setResult(page);
		 }catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

	 /**
	  * 根据条件查询账单
	  * @param
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "查询账单")
	 @ApiOperation(value="查询账单", notes="查询账单")
	 @PostMapping(value = "/selectBillsAll")
	 public Result<IPage<ChargeBills>> selectBillsAll(@RequestBody ChargeBills chargeBills,
														 HttpServletRequest req) {
		 Result<IPage<ChargeBills>> result = new Result<IPage<ChargeBills>>();
		 try {
		 	//直接查询所有信息，java分页
			 Page<ChargeBills> page = new Page<ChargeBills>(1, Integer.MAX_VALUE);
			 List<ChargeBills> chargeBillsList = chargeBillsService.getChargeBillsAll(page,chargeBills);
			 page.setTotal(chargeBillsList.size());
			 int pageNo = (chargeBills.getPageNo() - 1) * chargeBills.getPageSize();
			 if(pageNo + chargeBills.getPageSize() > chargeBillsList.size()){
			 	chargeBillsList = chargeBillsList.subList(pageNo, chargeBillsList.size());
			 }else {
			 	chargeBillsList = chargeBillsList.subList(pageNo, pageNo+chargeBills.getPageSize());
			 }
			 page.setRecords(chargeBillsList);
			 result.setSuccess(true);
			 result.setResult(page);
		 }catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }


	 /**
	  * 合并收费
	  * @return
	  */
	 @PostMapping(value = "/getByRoomBills")
	 public Result<List<ChargeBills>> getByRoomBills(@RequestBody ChargeBills chargeBills) {
		 Result<List<ChargeBills>> result = new Result<>();
		 List<ChargeBills> list = new ArrayList<ChargeBills>();
		 try {
			 list = chargeBillsService.getByRoomBillss(chargeBills);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return result;
	 }

     /**
      * 账单拆分
      * @return
      */
     @RequestMapping(value = "/splitBills")
     public Result<String> splitBills(@RequestBody ChargeBills chargeBills) {
		 try {
			 return chargeBillsService.splitBills(chargeBills);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return Result.error("系统繁忙,拆分失败");
     }

	 /**
	  * 已收账单进行退票
	  * @return
	  */
	 @RequestMapping(value = "/openInvoiceInfo")
	 public Result<ChargeInvoice> openInvoiceInfo(@RequestBody ChargeInvoice chargeInvoice) {
		 String  result = "";
		 try {
			 result = chargeBillsService.openInvoiceInfo(chargeInvoice);
		 } catch (Exception e) {
			 log.error(e.getMessage(),e);
		 }
		 return  Result.ok(result);
	 }



     /**
      * 收费情况导出
      * @param
      * @param
      * @return
      */
     @PostMapping(value = "/getBillsExportXls")
     public ModelAndView getBillsExportXls(@RequestBody ChargeBills chargeBills, HttpServletResponse response) {
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 LoginUser user = SsoUtil.getLoginUser();
		 List<ChargeBills> chargeBillsList = chargeBillsService.getChargeBillsAll(null,chargeBills);
		 //导出文件名称
		 mv.addObject(NormalExcelConstants.FILE_NAME, "账单详情");
		 mv.addObject(NormalExcelConstants.CLASS, ChargeBills.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("账单详情", "导出人:" + user.getRealname(), "导出信息"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, chargeBillsList);
		 return mv;
         /*SimpleDateFormat kpsmf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         XSSFWorkbook book = new XSSFWorkbook();
         try {
             XSSFSheet sheet = book.createSheet("mySheent");
             List<ChargeBills> list= chargeBillsService.selectBillsAll(chargeBills);
             String [] vals ={"楼宇名称","房间名称","业主名称","租户名称","收费项目","应收年月","应收金额","收款日期","收款方式","收款人","票据簿编号","票据编号","账单备注"};
			 XSSFCellStyle style = book.createCellStyle();
			 //居中
			 style.setAlignment(HorizontalAlignment.CENTER);
			 style.setVerticalAlignment(VerticalAlignment.CENTER);
			 //border
			 style.setBorderLeft(BorderStyle.THIN);
			 style.setBorderTop(BorderStyle.THIN);
			 style.setBorderRight(BorderStyle.THIN);
			 style.setBorderBottom(BorderStyle.THIN);
			 XSSFRow row = sheet.createRow(0);
			 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, vals.length-1));
			 row.setHeight((short) 0x349);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("账单详情");
			 cell.setCellStyle(style);
			 row = sheet.createRow(1);
			 for (int i = 0; i < vals.length; i++) {
				 cell = row.createCell(i);
				 cell.setCellValue(vals[i]);
				 cell.setCellStyle(style);
			 }
             if(list != null && list.size()>0){
                 for(int i = 0;i<list.size();i++){
                     ChargeBills bill = list.get(i);
                     String zjSkrq = "";
                     if(bill.getZjSkrq() !=null){
                         zjSkrq = kpsmf.format(bill.getZjSkrq());
                     }
                     String[] vals2 = {bill.getFloorName(),bill.getRoomName(),bill.getCustomerName(),
                             bill.getRentName(),bill.getFeeName(),bill.getZjCny(),
                             bill.getZjJe().toString(),zjSkrq,bill.getPayTypeStr(),bill.getPayuserName()
                                ,bill.getInvoiceGrnno(),bill.getInvoiceNo(),bill.getBillsExp()};
                     createExcel(sheet, i+2, vals2,style);
                 }
                 book.write(generateResponseExcel("账单详情",response));
             }
         }catch(Exception e){
             e.printStackTrace();
         }*/
     }
     /**
        * @param excelName
        *   要生成的文件名字
        * @return
        * @throws IOException
        */
     private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException {
         excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8");
         response.setContentType("application/vnd.ms-excel;charset=utf-8");
         response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
         return response.getOutputStream();
     }
     private void createExcel(XSSFSheet sheet, int rowNo, String[] vals, XSSFCellStyle style)  {
         if (vals.length > 0) {
             XSSFRow row = sheet.createRow(rowNo);
             for (int i = 0; i < vals.length; i++) {
                 String val = vals[i];
                 XSSFCell cell = row.createCell(i);
                 cell.setCellValue(val);
				 cell.setCellStyle(style);
             }
         }
     }

	 /**
	  * 根据账单ID集合获取账单信息
	  * @return
	  */
	 @PostMapping(value = "/getFromBles")
	 public Result<ChargeInvoice> getFromBles(@RequestBody ChargeBills chargeBills){
		 Result<ChargeInvoice> result = new Result<>();
		 try {
			 ChargeInvoice invoice = chargeBillsService.getBillsDetails(chargeBills);
			 result.setResult(invoice);
			 result.setSuccess(true);
		 }catch (Exception e){
			 log.error(e.getMessage(),e);
		 }
		 return  result;
	 }


}
